package amz

import (
	"errors"
	css "github.com/moovweb/gokogiri/css"
	"log"
	"strconv"
	"strings"
)

type USAsin struct {
	BaseAsin
}

func (asin *USAsin) Title() (title string) {
	nodes, err := asin.Doc.Root().Search(css.Convert("#btAsinTitle", css.GLOBAL))
	if err != nil {
		panic(err)
	}
	if len(nodes) != 1 {
		panic(errors.New("根据 id 查询 title 失败"))
	}
	return nodes[0].Content()
}

func (asin *USAsin) ReviewRating() (rating float64) {
	nodes, err := asin.Doc.Root().Search(css.Convert("#handleBuy .asinReviewsSummary > a span.swSprite", css.GLOBAL))
	if err != nil {
		panic(err)
	}
	if len(nodes) != 1 {
		log.Println(nodes)
		panic(errors.New("查询到多余一个的 ReviewRating 节点. 共 " + strconv.Itoa(len(nodes)) + " 个节点."))
	}

	text := nodes[0].Content()
	rating, err = strconv.ParseFloat(strings.Split(text, " ")[0], 64)
	return rating
}
